package soft_pattern.design_pattern.dp_2_structural;

/* 代理模式 */

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

interface Obj {
    void method();
}

class ObjImpl implements Obj {
    @Override
    public void method() {
        System.out.println("method");
    }
}

class ProxyHandler implements InvocationHandler {
    final private Object target;

    public ProxyHandler(Object target) {
        this.target = target;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("Before invoking " + method.getName());
        Object result = method.invoke(target, args);
        System.out.println("After invoking " + method.getName());
        return result;
    }
}

public class ProxyPattern {
    public static void main(String[] args) {
        ObjImpl obj = new ObjImpl();
        ProxyHandler proxyHandler = new ProxyHandler(obj);

        Obj objProxy = (Obj) Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(), proxyHandler);
        objProxy.method();
    }
}